import { is } from './is';

function keys(v) {
    const key_arr = v.split(/\./);
    let last_key = key_arr.pop();
    return {
        arr: key_arr.slice(),
        key_arr,
        last_key,
    };
}

export function setter(o, key, v, fill = true) {
    if (fill) {
        o = o || {};
    }
    const { key_arr, last_key } = keys(key);

    let p = o;
    while (key_arr.length) {
        const n_key = key_arr.shift();
        let v = p[n_key];
        if (!is.setter(v)) {
            if (fill) {
                v = {};
                p[n_key] = v;
            } else {
                throw new Error(`${n_key} is not a setter`);
            }
        }
        p = v;
    }

    p[last_key] = v;
}
export function getter(o, key) {
    const { key_arr, last_key } = keys(key);

    let p = o;
    while (key_arr.length) {
        const v = p[key_arr.shift()];
        if (is.non(v)) return v;
        p = v;
    }
    return p?.[last_key];
}

export function objectGetSet(o, key, value) {
    if (!o) return null;
    if (!key) return o;
    if (!value) return getter(o, key);
    setter(o, key, value);
}